package com.hxzy.yygh.msm.controller;

import com.hxzy.yygh.common.result.Result;
import com.hxzy.yygh.msm.service.MsmService;
import com.hxzy.yygh.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Api(tags = "短信发送模块")
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    //发送手机短信验证码
    @ApiOperation(value = "阿里云短信发送接口")
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone){
        //若redis中有验证码,先redis中获取验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return Result.ok();
        }

        //若redis中没有验证码，则先生成一个验证码
        code = RandomUtil.getFourBitRandom();

        //调用service方法，发送阿里云sms短信
        boolean isSend = msmService.send(phone, code);

        //将生成的验证码存入redis中，并设置有效时间
        if (isSend){
            redisTemplate.opsForValue().set(phone, code,2, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail().message("发送短信失败");
        }
    }

}
